import socket
import logging
import selectors
import datetime

FORMAT = "%(asctime)s %(threadName)s %(thread)d %(message)s"
logging.basicConfig(format=FORMAT,level=logging.INFO)

class Chat_Server_IO:
    def __init__(self):
        self.server = socket.socket()
        self.server.bind(('127.0.0.1',60000))
        self.server.listen()
        self.server.setblocking(False)
        self.selector = selectors.DefaultSelector()
        self.clients = set()

    def start(self):
        self.selector.register(self.server, selectors.EVENT_READ, self.accept)
        while True:
            events = self.selector.select()
            print(len(events), '+++++++')
            for key, mask in events:
                logging.info(key)
                key.data(key.fileobj, mask)

    def accept(self,sock:socket.socket,mask):
        print('accept fn ~~~~~~~~~')
        newsock,raddr = sock.accept()
        newsock.setblocking(False)
        self.clients.add(newsock)
        self.selector.register(newsock,selectors.EVENT_READ,self.recv)


    def recv(self,clientsock:socket.socket,mask):
        print('recv function ~~~~~~~~~')
        #try:
        data = clientsock.recv(1024)
        if data.decode() == '' or data.decode() == 'quit':
            clientsock.close()
            self.selector.unregister(clientsock)
            self.clients.remove(clientsock)
            return
        msg = "{}.From {}:{} .msg={}".format(datetime.datetime.now(),*clientsock.getsockname(),data.decode())
        logging.info(msg)
        for client in self.clients:
            if client == clientsock:
                continue
            client.send(msg.encode())

cs = Chat_Server_IO()
cs.start()

